package com.zhiyuan.audio;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbConfiguration;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.media.AudioDeviceInfo;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Build;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class AudioManager {
    private static final String TAG = "AudioManager";

    // 音频参数配置
    private static final int SAMPLE_RATE = 44100;
    private static final int CHANNEL_CONFIG_IN = AudioFormat.CHANNEL_IN_MONO;
    private static final int CHANNEL_CONFIG_OUT = AudioFormat.CHANNEL_OUT_MONO;
    private static final int AUDIO_FORMAT = AudioFormat.ENCODING_PCM_16BIT;

    private Context context;
    private AudioCallback callback;

    // 录音相关
    private AudioRecord audioRecord;
    private boolean isRecording = false;
    private Thread recordingThread;
    private String audioFilePath;

    // PCM数据流相关
    private boolean isPcmStreaming = false;
    private Thread pcmStreamingThread;
    private List<PcmDataListener> pcmDataListeners;

    // 播放相关
    private AudioTrack audioTrack;
    private boolean isPlaying = false;
    private Thread playbackThread;

    // 设备管理
    private android.media.AudioManager systemAudioManager;
    private List<AudioDevice> discoveredDevices;
    private AudioDevice selectedDevice;

    // USB设备管理
    private UsbManager usbManager;
    private UsbDevice connectedUsbAudioDevice;

    //PCM数据监听接口
    public interface PcmDataListener{
        /**
         * 实时接收PCM音频数据
         * @param pcmData PCM音频数据字节数组
         * @param bytesRead 实际读取的字节数
         * @param sampleRate 采样率
         * @param channelCount 声道数
         * @param audioFormat 音频格式
         */
        void onPcmDataReceived(byte[] pcmData, int bytesRead, int sampleRate, int channelCount, int audioFormat);

        /**
         * PCM数据流开始
         */
        void onPcmStreamStarted();

        /**
         * PCM数据流停止
         */
        void onPcmStreamStopped();

        /**
         * PCM数据流出错
         */
        void onPcmStreamError(String error);
    }

    public interface AudioCallback {
        void onDeviceFound(AudioDevice device);
        void onRecordingStarted();
        void onRecordingStopped();
        void onPlaybackStarted();
        void onPlaybackStopped();
        void onError(String error);

        void onMuteStateChanged(AudioDevice device, boolean muted);
        void onVolumeChanged(AudioDevice device, float volume);
        void onMuteUnsupported(AudioDevice device, String reason);
    }

    public AudioManager(Context context, AudioCallback callback) {
        this.context = context;
        this.callback = callback;
        this.discoveredDevices = new ArrayList<>();
        this.pcmDataListeners = new CopyOnWriteArrayList<>();

        systemAudioManager = (android.media.AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);

        // 设置音频文件路径
        audioFilePath = context.getExternalFilesDir(null) + "/recorded_audio.pcm";

        // 注册USB设备监听
        registerUsbReceiver();
    }


    /**
     * 添加PCM数据监听器
     */
    public void addPcmDataListener(PcmDataListener listener) {
        if (listener != null && !pcmDataListeners.contains(listener)) {
            pcmDataListeners.add(listener);
            Log.d(TAG, "添加PCM数据监听器，当前监听器数量: " + pcmDataListeners.size());
        }
    }

    /**
     * 移除PCM数据监听器
     */
    public void removePcmDataListener(PcmDataListener listener) {
        if (listener != null) {
            pcmDataListeners.remove(listener);
            Log.d(TAG, "移除PCM数据监听器，当前监听器数量: " + pcmDataListeners.size());
        }
    }

    /**
     * 清除所有PCM数据监听器
     */
    public void clearPcmDataListeners() {
        pcmDataListeners.clear();
        Log.d(TAG, "清除所有PCM数据监听器");
    }

    /**
     * 开始PCM数据流（不保存文件，只获取数据）
     */
    public void startPcmStreaming() {
        if (isPcmStreaming) {
            Log.w(TAG, "PCM数据流已在进行中");
            return;
        }

        if (pcmDataListeners.isEmpty()) {
            Log.w(TAG, "没有PCM数据监听器，无法开始数据流");
            callback.onError("请先添加PCM数据监听器");
            return;
        }

        try {
            int bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG_IN, AUDIO_FORMAT);
            if (bufferSize == AudioRecord.ERROR_BAD_VALUE || bufferSize == AudioRecord.ERROR) {
                callback.onError("无法获取录音缓冲区大小");
                return;
            }

            int audioSource = getAudioSourceForDevice(selectedDevice);

            audioRecord = new AudioRecord(
                    audioSource,
                    SAMPLE_RATE,
                    CHANNEL_CONFIG_IN,
                    AUDIO_FORMAT,
                    bufferSize * 2
            );

            if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
                callback.onError("AudioRecord初始化失败");
                return;
            }

            isPcmStreaming = true;
            audioRecord.startRecording();

            pcmStreamingThread = new Thread(this::pcmStreamingLoop);
            pcmStreamingThread.start();

            // 通知所有监听器
            for (PcmDataListener listener : pcmDataListeners) {
                try {
                    listener.onPcmStreamStarted();
                } catch (Exception e) {
                    Log.e(TAG, "PCM监听器回调出错", e);
                }
            }

            Log.d(TAG, "开始PCM数据流");

        } catch (SecurityException e) {
            callback.onError("录音权限被拒绝");
        } catch (Exception e) {
            callback.onError("开始PCM数据流失败: " + e.getMessage());
        }
    }

    /**
     * 停止PCM数据流
     */
    public void stopPcmStreaming() {
        if (!isPcmStreaming) {
            Log.w(TAG, "当前没有PCM数据流进行");
            return;
        }

        isPcmStreaming = false;

        if (audioRecord != null) {
            try {
                audioRecord.stop();
            } catch (IllegalStateException e) {
                Log.e(TAG, "停止PCM数据流时发生错误", e);
            }
            audioRecord.release();
            audioRecord = null;
        }

        if (pcmStreamingThread != null) {
            try {
                pcmStreamingThread.join(1000);
            } catch (InterruptedException e) {
                Log.e(TAG, "等待PCM数据流线程结束时被中断", e);
            }
            pcmStreamingThread = null;
        }

        // 通知所有监听器
        for (PcmDataListener listener : pcmDataListeners) {
            try {
                listener.onPcmStreamStopped();
            } catch (Exception e) {
                Log.e(TAG, "PCM监听器回调出错", e);
            }
        }

        Log.d(TAG, "PCM数据流已停止");
    }

    /**
     * PCM数据流循环
     */
    private void pcmStreamingLoop() {
        byte[] buffer = new byte[1024];
        int channelCount = getChannelCount(CHANNEL_CONFIG_IN);

        try {
            Log.d(TAG, "开始PCM数据流循环");

            while (isPcmStreaming && audioRecord != null) {
                int bytesRead = audioRecord.read(buffer, 0, buffer.length);

                if (bytesRead > 0) {
                    // 将数据分发给所有监听器
                    for (PcmDataListener listener : pcmDataListeners) {
                        try {
                            // 创建数据副本，避免并发修改
                            byte[] dataCopy = new byte[bytesRead];
                            System.arraycopy(buffer, 0, dataCopy, 0, bytesRead);

                            listener.onPcmDataReceived(dataCopy, bytesRead, SAMPLE_RATE, channelCount, AUDIO_FORMAT);
                        } catch (Exception e) {
                            Log.e(TAG, "PCM数据监听器处理出错", e);
                        }
                    }
                } else if (bytesRead == AudioRecord.ERROR_INVALID_OPERATION) {
                    Log.e(TAG, "PCM数据流操作无效");
                    break;
                } else if (bytesRead == AudioRecord.ERROR_BAD_VALUE) {
                    Log.e(TAG, "PCM数据流参数错误");
                    break;
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "PCM数据流循环异常", e);

            // 通知所有监听器发生错误
            for (PcmDataListener listener : pcmDataListeners) {
                try {
                    listener.onPcmStreamError("PCM数据流异常: " + e.getMessage());
                } catch (Exception ex) {
                    Log.e(TAG, "PCM监听器错误回调出错", ex);
                }
            }
        }

        Log.d(TAG, "PCM数据流循环结束");
    }

    /**
     * 同时开始录音和PCM数据流
     */
    public void startRecordingWithPcmStream() {
        if (isRecording || isPcmStreaming) {
            Log.w(TAG, "录音或PCM数据流已在进行中");
            return;
        }

        try {
            int bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG_IN, AUDIO_FORMAT);
            if (bufferSize == AudioRecord.ERROR_BAD_VALUE || bufferSize == AudioRecord.ERROR) {
                callback.onError("无法获取录音缓冲区大小");
                return;
            }

            int audioSource = getAudioSourceForDevice(selectedDevice);

            audioRecord = new AudioRecord(
                    audioSource,
                    SAMPLE_RATE,
                    CHANNEL_CONFIG_IN,
                    AUDIO_FORMAT,
                    bufferSize * 2
            );

            if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
                callback.onError("AudioRecord初始化失败");
                return;
            }

            isRecording = true;
            isPcmStreaming = !pcmDataListeners.isEmpty(); // 只有在有监听器时才启用PCM流
            audioRecord.startRecording();

            recordingThread = new Thread(this::recordingWithPcmLoop);
            recordingThread.start();

            callback.onRecordingStarted();

            // 如果有PCM监听器，通知开始
            if (isPcmStreaming) {
                for (PcmDataListener listener : pcmDataListeners) {
                    try {
                        listener.onPcmStreamStarted();
                    } catch (Exception e) {
                        Log.e(TAG, "PCM监听器回调出错", e);
                    }
                }
            }

            Log.d(TAG, "开始录音" + (isPcmStreaming ? "并启用PCM数据流" : ""));

        } catch (SecurityException e) {
            callback.onError("录音权限被拒绝");
        } catch (Exception e) {
            callback.onError("开始录音失败: " + e.getMessage());
        }
    }

    /**
     * 录音+PCM数据流的组合循环
     */
    private void recordingWithPcmLoop() {
        FileOutputStream fos = null;
        byte[] buffer = new byte[1024];
        int channelCount = getChannelCount(CHANNEL_CONFIG_IN);

        try {
            fos = new FileOutputStream(audioFilePath);
            Log.d(TAG, "录音文件保存路径: " + audioFilePath);

            while ((isRecording || isPcmStreaming) && audioRecord != null) {
                int bytesRead = audioRecord.read(buffer, 0, buffer.length);
                if (bytesRead > 0) {
                    // 保存到文件（如果正在录音）
                    if (isRecording && fos != null) {
                        fos.write(buffer, 0, bytesRead);
                    }

                    // 分发给PCM监听器（如果启用了PCM流）
                    if (isPcmStreaming) {
                        for (PcmDataListener listener : pcmDataListeners) {
                            try {
                                byte[] dataCopy = new byte[bytesRead];
                                System.arraycopy(buffer, 0, dataCopy, 0, bytesRead);
                                listener.onPcmDataReceived(dataCopy, bytesRead, SAMPLE_RATE, channelCount, AUDIO_FORMAT);
                            } catch (Exception e) {
                                Log.e(TAG, "PCM数据监听器处理出错", e);
                            }
                        }
                    }
                } else if (bytesRead == AudioRecord.ERROR_INVALID_OPERATION) {
                    Log.e(TAG, "录音操作无效");
                    break;
                }
            }
        } catch (IOException e) {
            callback.onError("录音写入文件失败: " + e.getMessage());
            Log.e(TAG, "录音文件写入错误", e);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 停止录音和PCM数据流
     */
    public void stopRecordingWithPcmStream() {
        boolean wasRecording = isRecording;
        boolean wasPcmStreaming = isPcmStreaming;

        isRecording = false;
        isPcmStreaming = false;

        if (audioRecord != null) {
            try {
                audioRecord.stop();
            } catch (IllegalStateException e) {
                Log.e(TAG, "停止录音时发生错误", e);
            }
            audioRecord.release();
            audioRecord = null;
        }

        if (recordingThread != null) {
            try {
                recordingThread.join(1000);
            } catch (InterruptedException e) {
                Log.e(TAG, "等待录音线程结束时被中断", e);
            }
            recordingThread = null;
        }

        if (wasRecording) {
            callback.onRecordingStopped();
        }

        if (wasPcmStreaming) {
            for (PcmDataListener listener : pcmDataListeners) {
                try {
                    listener.onPcmStreamStopped();
                } catch (Exception e) {
                    Log.e(TAG, "PCM监听器回调出错", e);
                }
            }
        }

        Log.d(TAG, "录音和PCM数据流已停止");
    }

    /**
     * 获取声道数
     */
    private int getChannelCount(int channelConfig) {
        switch (channelConfig) {
            case AudioFormat.CHANNEL_IN_MONO:
                return 1;
            case AudioFormat.CHANNEL_IN_STEREO:
                return 2;
            default:
                return 1;
        }
    }

    /**
     * 是否正在进行PCM数据流
     */
    public boolean isPcmStreaming() {
        return isPcmStreaming;
    }

    /**
     * 获取当前音频参数
     */
    public AudioParams getCurrentAudioParams() {
        return new AudioParams(SAMPLE_RATE, getChannelCount(CHANNEL_CONFIG_IN), AUDIO_FORMAT);
    }

    /**
     * 音频参数类
     */
    public static class AudioParams {
        public final int sampleRate;
        public final int channelCount;
        public final int audioFormat;

        public AudioParams(int sampleRate, int channelCount, int audioFormat) {
            this.sampleRate = sampleRate;
            this.channelCount = channelCount;
            this.audioFormat = audioFormat;
        }

        @Override
        public String toString() {
            return String.format("AudioParams{sampleRate=%d, channelCount=%d, audioFormat=%d}",
                    sampleRate, channelCount, audioFormat);
        }
    }

    // ============== 改进的设备发现功能 ==============

    public void discoverDevices() {
        discoveredDevices.clear();

        Log.d(TAG, "开始发现音频设备...");

        // 发现内置音频设备
       // discoverBuiltInDevices();

        // 发现USB音频设备 - 改进版本
        discoverUsbAudioDevicesEnhanced();

        // 发现蓝牙音频设备
       // discoverBluetoothDevices();

//        // 使用Android AudioManager发现系统音频设备
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//            discoverSystemAudioDevices();
//        }

        Log.d(TAG, "设备发现完成，共找到 " + discoveredDevices.size() + " 个设备");
    }

    private void discoverBuiltInDevices() {
        // 内置麦克风
        AudioDevice micDevice = new AudioDevice(
                "built_in_mic",
                "内置麦克风",
                AudioDevice.Type.MICROPHONE,
                true
        );
        discoveredDevices.add(micDevice);
        callback.onDeviceFound(micDevice);

        // 内置扬声器
        AudioDevice speakerDevice = new AudioDevice(
                "built_in_speaker",
                "内置扬声器",
                AudioDevice.Type.SPEAKER,
                true
        );
        discoveredDevices.add(speakerDevice);
        callback.onDeviceFound(speakerDevice);
    }

    private void discoverUsbAudioDevicesEnhanced() {
        if (usbManager == null) {
            Log.w(TAG, "UsbManager为空，无法发现USB设备");
            return;
        }

        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
        Log.d(TAG, "USB设备总数: " + deviceList.size());

        for (UsbDevice device : deviceList.values()) {
            Log.d(TAG, "检查USB设备: " + device.getDeviceName() +
                    ", VID: " + Integer.toHexString(device.getVendorId()) +
                    ", PID: " + Integer.toHexString(device.getProductId()) +
                    ", 产品名: " + device.getProductName());

            // 使用更宽松的条件检查是否为音频设备
            if (isUsbAudioDeviceEnhanced(device)) {
                String deviceName = device.getProductName();
                if (deviceName == null || deviceName.trim().isEmpty()) {
                    deviceName = "USB音频设备 (" +
                            Integer.toHexString(device.getVendorId()) + ":" +
                            Integer.toHexString(device.getProductId()) + ")";
                }

                AudioDevice audioDevice = new AudioDevice(
                        "usb_" + device.getDeviceId(),
                        deviceName,
                        AudioDevice.Type.USB_AUDIO,
                        true
                );

                // 检查是否已经存在相同设备
                boolean alreadyExists = discoveredDevices.stream()
                        .anyMatch(d -> d.getId().equals(audioDevice.getId()));

                if (!alreadyExists) {
                    discoveredDevices.add(audioDevice);
                    callback.onDeviceFound(audioDevice);
                    Log.d(TAG, "发现USB音频设备: " + audioDevice.getName());
                }
            }
        }
    }

    private boolean isUsbAudioDeviceEnhanced(UsbDevice device) {
        try {
            // 方法1: 检查USB设备类别
            for (int i = 0; i < device.getConfigurationCount(); i++) {
                UsbConfiguration config = device.getConfiguration(i);
                for (int j = 0; j < config.getInterfaceCount(); j++) {
                    UsbInterface intf = config.getInterface(j);

                    // 音频设备类别码为1
                    if (intf.getInterfaceClass() == 1) {
                        Log.d(TAG, "通过接口类别发现音频设备: " + device.getProductName());
                        return true;
                    }

                    // 某些设备可能使用Vendor Specific类别 (255)
                    if (intf.getInterfaceClass() == 255) {
                        // 检查是否是已知的音频设备厂商
                        if (isKnownAudioVendor(device.getVendorId())) {
                            Log.d(TAG, "通过厂商ID识别为音频设备: " + device.getProductName());
                            return true;
                        }
                    }
                }
            }

            // 方法2: 通过产品名称识别
            String productName = device.getProductName();
            if (productName != null) {
                String lowerName = productName.toLowerCase();
                if (lowerName.contains("audio") ||
                        lowerName.contains("sound") ||
                        lowerName.contains("headset") ||
                        lowerName.contains("headphone") ||
                        lowerName.contains("speaker") ||
                        lowerName.contains("microphone") ||
                        lowerName.contains("codec")) {
                    Log.d(TAG, "通过产品名称识别为音频设备: " + productName);
                    return true;
                }
            }

            // 方法3: 通过厂商ID识别已知音频设备厂商
            if (isKnownAudioVendor(device.getVendorId())) {
                Log.d(TAG, "通过厂商ID识别为可能的音频设备: VID=" +
                        Integer.toHexString(device.getVendorId()));
                return true;
            }

        } catch (Exception e) {
            Log.e(TAG, "检查USB音频设备时发生错误", e);
        }

        return false;
    }

    private boolean isKnownAudioVendor(int vendorId) {
        // 常见音频设备厂商的VID列表
        int[] knownAudioVendorIds = {
                0x041e, // Creative Technology
                0x0d8c, // C-Media Electronics
                0x08bb, // Texas Instruments
                0x0b05, // ASUSTek Computer
                0x046d, // Logitech
                0x1235, // Focusrite-Novation
                0x0763, // M-Audio
                0x194f, // PreSonus Audio Electronics
                0x0582, // Roland
                0x16c0, // Van Ooijen Technische Informatica
                0x262a, // SAVITECH
                0x05ac, // Apple Inc.
                0x0bda, // Realtek Semiconductor
                0x1397, // BEHRINGER International
                0x2109, // VIA Labs
                0x17ef, // Lenovo
                0x8086, // Intel
                0x1b3f, // Generalplus Technology
                0x18d1, // Google Inc.
        };

        for (int knownVid : knownAudioVendorIds) {
            if (vendorId == knownVid) {
                return true;
            }
        }
        return false;
    }

    private void discoverSystemAudioDevices() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                AudioDeviceInfo[] devices = systemAudioManager.getDevices(
                        android.media.AudioManager.GET_DEVICES_ALL);

                for (AudioDeviceInfo deviceInfo : devices) {
                    // 只处理USB音频设备，避免重复添加内置设备
                    if (deviceInfo.getType() == AudioDeviceInfo.TYPE_USB_DEVICE ||
                            deviceInfo.getType() == AudioDeviceInfo.TYPE_USB_HEADSET ||
                            deviceInfo.getType() == AudioDeviceInfo.TYPE_USB_ACCESSORY) {

                        String deviceName = deviceInfo.getProductName() != null ?
                                deviceInfo.getProductName().toString() :
                                "系统USB音频设备";

                        AudioDevice audioDevice = new AudioDevice(
                                "system_usb_" + deviceInfo.getId(),
                                deviceName,
                                AudioDevice.Type.USB_AUDIO,
                                true
                        );

                        // 检查是否已经存在相同设备
                        boolean alreadyExists = discoveredDevices.stream()
                                .anyMatch(d -> d.getName().equals(audioDevice.getName()));

                        if (!alreadyExists) {
                            discoveredDevices.add(audioDevice);
                            callback.onDeviceFound(audioDevice);
                            Log.d(TAG, "通过系统API发现USB音频设备: " + audioDevice.getName());
                        }
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "通过系统API发现设备时发生错误", e);
            }
        }
    }

    private void discoverBluetoothDevices() {
        if (systemAudioManager.isBluetoothA2dpOn()) {
            AudioDevice btDevice = new AudioDevice(
                    "bluetooth_audio",
                    "蓝牙音频设备",
                    AudioDevice.Type.BLUETOOTH,
                    true
            );
            discoveredDevices.add(btDevice);
            callback.onDeviceFound(btDevice);
        }
    }

    // ============== 静音控制功能 ==============

    public void setDeviceMute(AudioDevice device, boolean mute) {
        if (device == null) {
            callback.onError("设备信息为空");
            return;
        }

        if (!device.isMuteSupported()) {
            callback.onMuteUnsupported(device, "设备不支持静音控制");
            return;
        }

        Log.d(TAG, "设置设备静音: " + device.getName() + ", 静音: " + mute);

        // 按优先级尝试不同的静音方法
        boolean success = false;

        // 方法1: 使用标准AudioManager API
        if (!success) {
            success = setMuteUsingStandardAPI(device, mute);
        }

        // 方法2: 使用USB控制传输（针对UAC设备）
        if (!success && device.getType() == AudioDevice.Type.USB_AUDIO) {
            success = setMuteUsingUSBControl(device, mute);
        }

        // 方法3: 使用反射调用隐藏API
        if (!success) {
            success = setMuteUsingReflection(device, mute);
        }

        // 方法4: 通过音量控制实现软件静音
        if (!success) {
            success = setMuteUsingVolumeControl(device, mute);
        }

        if (success) {
            device.setMuted(mute);
            callback.onMuteStateChanged(device, mute);
            Log.d(TAG, "设备静音设置成功: " + device.getName() + " -> " + mute);
        } else {
            callback.onError("所有静音控制方法都失败了");
        }
    }

    public boolean getDeviceMuteState(AudioDevice device) {
        if (device == null) return false;

        try {
            int streamType = getStreamTypeForDevice(device);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                boolean systemMuted = systemAudioManager.isStreamMute(streamType);
                device.setMuted(systemMuted);
                return systemMuted;
            } else {
                int volume = systemAudioManager.getStreamVolume(streamType);
                boolean muted = (volume == 0);
                device.setMuted(muted);
                return muted;
            }

        } catch (Exception e) {
            Log.e(TAG, "获取静音状态失败", e);
            return device.isMuted();
        }
    }

    public void toggleDeviceMute(AudioDevice device) {
        boolean currentState = getDeviceMuteState(device);
        setDeviceMute(device, !currentState);
    }

    public void setDeviceVolume(AudioDevice device, float volume) {
        if (device == null) {
            callback.onError("设备信息为空");
            return;
        }

        volume = Math.max(0.0f, Math.min(1.0f, volume));

        try {
            int streamType = getStreamTypeForDevice(device);
            int maxVolume = systemAudioManager.getStreamMaxVolume(streamType);
            int targetVolume = Math.round(volume * maxVolume);

            systemAudioManager.setStreamVolume(streamType, targetVolume, 0);

            device.setVolume(volume);
            callback.onVolumeChanged(device, volume);

            Log.d(TAG, "设备音量设置成功: " + device.getName() + " -> " + volume);

        } catch (Exception e) {
            Log.e(TAG, "设置音量失败", e);
            callback.onError("设置音量失败: " + e.getMessage());
        }
    }

    public float getDeviceVolume(AudioDevice device) {
        if (device == null) return 0.0f;

        try {
            int streamType = getStreamTypeForDevice(device);
            int currentVolume = systemAudioManager.getStreamVolume(streamType);
            int maxVolume = systemAudioManager.getStreamMaxVolume(streamType);

            float volume = (float) currentVolume / maxVolume;
            device.setVolume(volume);

            return volume;

        } catch (Exception e) {
            Log.e(TAG, "获取音量失败", e);
            return device.getVolume();
        }
    }

    // ============== 静音实现方法 ==============

    private boolean setMuteUsingStandardAPI(AudioDevice device, boolean mute) {
        try {
            int streamType = getStreamTypeForDevice(device);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (mute) {
                    systemAudioManager.adjustStreamVolume(streamType, android.media.AudioManager.ADJUST_MUTE, 0);
                } else {
                    systemAudioManager.adjustStreamVolume(streamType, android.media.AudioManager.ADJUST_UNMUTE, 0);
                }

                boolean actualState = systemAudioManager.isStreamMute(streamType);
                Log.d(TAG, "标准API静音结果: 期望=" + mute + ", 实际=" + actualState);
                return actualState == mute;
            }

        } catch (Exception e) {
            Log.e(TAG, "标准API静音失败", e);
        }
        return false;
    }

    private boolean setMuteUsingUSBControl(AudioDevice device, boolean mute) {
        try {
            UsbDevice usbDevice = findUsbDeviceById(device.getId());
            if (usbDevice == null) {
                Log.w(TAG, "找不到对应的USB设备: " + device.getId());
                return false;
            }

            UsbDeviceConnection connection = usbManager.openDevice(usbDevice);
            if (connection == null) {
                Log.w(TAG, "无法打开USB设备连接");
                return false;
            }

            try {
                int bmRequestType = 0x21;
                int bRequest = 0x01;
                int wValue = 0x0200;
                int wIndex = getUsbAudioControlInterface(usbDevice);

                byte[] data = new byte[1];
                data[0] = mute ? (byte) 1 : (byte) 0;

                int result = connection.controlTransfer(
                        bmRequestType, bRequest, wValue, wIndex, data, data.length, 1000);

                Log.d(TAG, "USB控制传输结果: " + result);
                return result >= 0;

            } finally {
                connection.close();
            }

        } catch (Exception e) {
            Log.e(TAG, "USB控制传输静音失败", e);
        }
        return false;
    }

    private boolean setMuteUsingReflection(AudioDevice device, boolean mute) {
        try {
            Class<?> audioManagerClass = android.media.AudioManager.class;

            Method[] methods = {
                    getMethodSafely(audioManagerClass, "setDeviceMute", int.class, boolean.class, String.class),
                    getMethodSafely(audioManagerClass, "setStreamMute", int.class, boolean.class),
                    getMethodSafely(audioManagerClass, "setMasterMute", boolean.class)
            };

            for (Method method : methods) {
                if (method != null) {
                    try {
                        method.setAccessible(true);

                        if (method.getName().equals("setDeviceMute")) {
                            method.invoke(systemAudioManager, getAndroidDeviceId(device), mute, context.getPackageName());
                        } else if (method.getName().equals("setStreamMute")) {
                            int streamType = getStreamTypeForDevice(device);
                            method.invoke(systemAudioManager, streamType, mute);
                        } else if (method.getName().equals("setMasterMute")) {
                            method.invoke(systemAudioManager, mute);
                        }

                        Log.d(TAG, "反射调用成功: " + method.getName());
                        return true;

                    } catch (Exception e) {
                        Log.d(TAG, "反射方法失败: " + method.getName() + " - " + e.getMessage());
                    }
                }
            }

        } catch (Exception e) {
            Log.e(TAG, "反射静音失败", e);
        }
        return false;
    }

    private boolean setMuteUsingVolumeControl(AudioDevice device, boolean mute) {
        try {
            if (mute) {
                float currentVolume = getDeviceVolume(device);
                device.setOriginalVolume(currentVolume);
                setDeviceVolume(device, 0.0f);
            } else {
                float originalVolume = device.getOriginalVolume();
                if (originalVolume > 0) {
                    setDeviceVolume(device, originalVolume);
                } else {
                    setDeviceVolume(device, 0.5f);
                }
            }

            Log.d(TAG, "音量控制静音成功");
            return true;

        } catch (Exception e) {
            Log.e(TAG, "音量控制静音失败", e);
        }
        return false;
    }

    // ============== 辅助方法 ==============

    private int getStreamTypeForDevice(AudioDevice device) {
        switch (device.getType()) {
            case MICROPHONE:
                return android.media.AudioManager.STREAM_VOICE_CALL;
            case USB_AUDIO:
            case SPEAKER:
            case BLUETOOTH:
            default:
                return android.media.AudioManager.STREAM_MUSIC;
        }
    }

    private UsbDevice findUsbDeviceById(String deviceId) {
        if (usbManager == null || deviceId == null) return null;

        if (deviceId.startsWith("usb_")) {
            try {
                int usbDeviceId = Integer.parseInt(deviceId.substring(4));

                for (UsbDevice device : usbManager.getDeviceList().values()) {
                    if (device.getDeviceId() == usbDeviceId) {
                        return device;
                    }
                }
            } catch (NumberFormatException e) {
                Log.e(TAG, "解析USB设备ID失败: " + deviceId);
            }
        } else if (deviceId.startsWith("system_usb_")) {
            // 对于通过系统API发现的设备，尝试通过名称匹配
            String targetName = null;
            for (AudioDevice audioDevice : discoveredDevices) {
                if (audioDevice.getId().equals(deviceId)) {
                    targetName = audioDevice.getName();
                    break;
                }
            }

            if (targetName != null) {
                for (UsbDevice device : usbManager.getDeviceList().values()) {
                    if (targetName.equals(device.getProductName())) {
                        return device;
                    }
                }
            }
        }
        return null;
    }

    private int getUsbAudioControlInterface(UsbDevice device) {
        for (int i = 0; i < device.getConfigurationCount(); i++) {
            UsbConfiguration config = device.getConfiguration(i);
            for (int j = 0; j < config.getInterfaceCount(); j++) {
                UsbInterface intf = config.getInterface(j);
                // 音频控制接口：类别=1，子类别=1
                if (intf.getInterfaceClass() == 1 && intf.getInterfaceSubclass() == 1) {
                    return intf.getId();
                }
            }
        }
        return 0; // 默认返回0
    }

    private int getAndroidDeviceId(AudioDevice device) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            try {
                AudioDeviceInfo[] devices =
                        systemAudioManager.getDevices(android.media.AudioManager.GET_DEVICES_ALL);

                for (AudioDeviceInfo androidDevice : devices) {
                    if (isMatchingDevice(device, androidDevice)) {
                        return androidDevice.getId();
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, "获取Android设备ID失败", e);
            }
        }
        return 0;
    }

    private boolean isMatchingDevice(AudioDevice customDevice, AudioDeviceInfo androidDevice) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int androidType = androidDevice.getType();
            AudioDevice.Type customType = customDevice.getType();

            switch (customType) {
                case USB_AUDIO:
                    return androidType == AudioDeviceInfo.TYPE_USB_DEVICE ||
                            androidType == AudioDeviceInfo.TYPE_USB_HEADSET ||
                            androidType == AudioDeviceInfo.TYPE_USB_ACCESSORY;
                case BLUETOOTH:
                    return androidType == AudioDeviceInfo.TYPE_BLUETOOTH_A2DP ||
                            androidType == AudioDeviceInfo.TYPE_BLUETOOTH_SCO;
                case MICROPHONE:
                    return androidType == AudioDeviceInfo.TYPE_BUILTIN_MIC;
                case SPEAKER:
                    return androidType == AudioDeviceInfo.TYPE_BUILTIN_SPEAKER;
            }
        }
        return false;
    }

    private Method getMethodSafely(Class<?> clazz, String methodName, Class<?>... parameterTypes) {
        try {
            return clazz.getDeclaredMethod(methodName, parameterTypes);
        } catch (NoSuchMethodException e) {
            return null;
        }
    }

    // ============== 原有功能保持不变 ==============

    // 设备选择
    public void selectDevice(AudioDevice device) {
        this.selectedDevice = device;
        configureAudioRoute(device);
        Log.d(TAG, "选择设备: " + device.getName());
    }

    private void configureAudioRoute(AudioDevice device) {
        switch (device.getType()) {
            case USB_AUDIO:
                systemAudioManager.setWiredHeadsetOn(true);
                break;
            case BLUETOOTH:
                systemAudioManager.setBluetoothA2dpOn(true);
                break;
            case MICROPHONE:
            case SPEAKER:
            default:
                systemAudioManager.setWiredHeadsetOn(false);
                systemAudioManager.setBluetoothA2dpOn(false);
                break;
        }
    }

    // 录音功能
    public void startRecording() {
        if (isRecording) {
            Log.w(TAG, "录音已在进行中");
            return;
        }

        try {
            int bufferSize = AudioRecord.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG_IN, AUDIO_FORMAT);
            if (bufferSize == AudioRecord.ERROR_BAD_VALUE || bufferSize == AudioRecord.ERROR) {
                callback.onError("无法获取录音缓冲区大小");
                return;
            }

            int audioSource = getAudioSourceForDevice(selectedDevice);

            audioRecord = new AudioRecord(
                    audioSource,
                    SAMPLE_RATE,
                    CHANNEL_CONFIG_IN,
                    AUDIO_FORMAT,
                    bufferSize * 2
            );

            if (audioRecord.getState() != AudioRecord.STATE_INITIALIZED) {
                callback.onError("AudioRecord初始化失败");
                return;
            }

            isRecording = true;
            audioRecord.startRecording();

            recordingThread = new Thread(this::recordingLoop);
            recordingThread.start();

            callback.onRecordingStarted();
            Log.d(TAG, "开始录音");

        } catch (SecurityException e) {
            callback.onError("录音权限被拒绝");
        } catch (Exception e) {
            callback.onError("开始录音失败: " + e.getMessage());
        }
    }

    private int getAudioSourceForDevice(AudioDevice device) {
        if (device == null) return MediaRecorder.AudioSource.MIC;

        switch (device.getType()) {
            case USB_AUDIO:
                return MediaRecorder.AudioSource.MIC;
            case BLUETOOTH:
                return MediaRecorder.AudioSource.MIC;
            case MICROPHONE:
            default:
                return MediaRecorder.AudioSource.MIC;
        }
    }

    private void recordingLoop() {
        FileOutputStream fos = null;
        byte[] buffer = new byte[1024];

        try {
            fos = new FileOutputStream(audioFilePath);
            Log.d(TAG, "录音文件保存路径: " + audioFilePath);

            while (isRecording && audioRecord != null) {
                int bytesRead = audioRecord.read(buffer, 0, buffer.length);
                if (bytesRead > 0) {
                    fos.write(buffer, 0, bytesRead);
                } else if (bytesRead == AudioRecord.ERROR_INVALID_OPERATION) {
                    Log.e(TAG, "录音操作无效");
                    break;
                }
            }
        } catch (IOException e) {
            callback.onError("录音写入文件失败: " + e.getMessage());
            Log.e(TAG, "录音文件写入错误", e);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void stopRecording() {
        if (!isRecording) {
            Log.w(TAG, "当前没有录音进行");
            return;
        }

        isRecording = false;

        if (audioRecord != null) {
            try {
                audioRecord.stop();
            } catch (IllegalStateException e) {
                Log.e(TAG, "停止录音时发生错误", e);
            }
            audioRecord.release();
            audioRecord = null;
        }

        if (recordingThread != null) {
            try {
                recordingThread.join(1000);
            } catch (InterruptedException e) {
                Log.e(TAG, "等待录音线程结束时被中断", e);
            }
            recordingThread = null;
        }

        callback.onRecordingStopped();
        Log.d(TAG, "录音已停止");
    }

    // 播放功能
    public void startPlayback() {
        if (isPlaying) {
            Log.w(TAG, "播放已在进行中");
            return;
        }

        File audioFile = new File(audioFilePath);
        if (!audioFile.exists()) {
            callback.onError("音频文件不存在，请先录音");
            return;
        }

        try {
            int bufferSize = AudioTrack.getMinBufferSize(SAMPLE_RATE, CHANNEL_CONFIG_OUT, AUDIO_FORMAT);
            if (bufferSize == AudioTrack.ERROR_BAD_VALUE || bufferSize == AudioTrack.ERROR) {
                callback.onError("无法获取播放缓冲区大小");
                return;
            }

            audioTrack = new AudioTrack(
                    android.media.AudioManager.STREAM_MUSIC,
                    SAMPLE_RATE,
                    CHANNEL_CONFIG_OUT,
                    AUDIO_FORMAT,
                    bufferSize * 2,
                    AudioTrack.MODE_STREAM
            );

            if (audioTrack.getState() != AudioTrack.STATE_INITIALIZED) {
                callback.onError("AudioTrack初始化失败");
                return;
            }

            isPlaying = true;
            audioTrack.play();

            playbackThread = new Thread(this::playbackLoop);
            playbackThread.start();

            callback.onPlaybackStarted();
            Log.d(TAG, "开始播放");

        } catch (Exception e) {
            callback.onError("开始播放失败: " + e.getMessage());
            Log.e(TAG, "播放启动错误", e);
        }
    }

    private void playbackLoop() {
        FileInputStream fis = null;
        byte[] buffer = new byte[1024];

        try {
            fis = new FileInputStream(audioFilePath);
            Log.d(TAG, "开始播放文件: " + audioFilePath);

            while (isPlaying && audioTrack != null) {
                int bytesRead = fis.read(buffer);
                if (bytesRead <= 0) {
                    break;
                }

                int bytesWritten = audioTrack.write(buffer, 0, bytesRead);
                if (bytesWritten < 0) {
                    Log.e(TAG, "播放写入错误: " + bytesWritten);
                    break;
                }
            }
        } catch (IOException e) {
            callback.onError("播放文件读取失败: " + e.getMessage());
            Log.e(TAG, "播放文件读取错误", e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (isPlaying) {
                stopPlayback();
            }
        }
    }

    public void stopPlayback() {
        if (!isPlaying) {
            Log.w(TAG, "当前没有播放进行");
            return;
        }

        isPlaying = false;

        if (audioTrack != null) {
            try {
                audioTrack.stop();
            } catch (IllegalStateException e) {
                Log.e(TAG, "停止播放时发生错误", e);
            }
            audioTrack.release();
            audioTrack = null;
        }

        if (playbackThread != null) {
            try {
                playbackThread.join(1000);
            } catch (InterruptedException e) {
                Log.e(TAG, "等待播放线程结束时被中断", e);
            }
            playbackThread = null;
        }

        callback.onPlaybackStopped();
        Log.d(TAG, "播放已停止");
    }

    // USB设备监听
    private void registerUsbReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);

        context.registerReceiver(usbReceiver, filter);
    }

    private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);

            if (device != null && isUsbAudioDeviceEnhanced(device)) {
                if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                    connectedUsbAudioDevice = device;
                    Log.d(TAG, "USB音频设备已连接: " + device.getProductName());
                    // 重新发现设备
                    discoverDevices();
                } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                    connectedUsbAudioDevice = null;
                    Log.d(TAG, "USB音频设备已断开: " + device.getProductName());
                    // 从已发现列表中移除
                    discoveredDevices.removeIf(d -> d.getId().contains("" + device.getDeviceId()));
                }
            }
        }
    };

    public void release() {
        Log.d(TAG, "释放AudioManager资源");
        stopRecording();
        stopPlayback();

        stopPcmStreaming();
        clearPcmDataListeners();

        try {
            context.unregisterReceiver(usbReceiver);
        } catch (IllegalArgumentException e) {
            Log.w(TAG, "USB接收器未注册");
        }
    }

    public List<AudioDevice> getDiscoveredDevices() {
        return new ArrayList<>(discoveredDevices);
    }

    public AudioDevice getSelectedDevice() {
        return selectedDevice;
    }

    public boolean isRecording() {
        return isRecording;
    }

    public boolean isPlaying() {
        return isPlaying;
    }
}